package com.example.remotecontrol.data.repository

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.remotecontrol.data.model.Scene
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

// 创建一个DataStore实例
private val Context.sceneDataStore by preferencesDataStore(name = "scenes")

/**
 * 场景仓库
 * 负责管理场景数据的存储和检索
 */
@Singleton
class SceneRepository @Inject constructor(
    @ApplicationContext private val context: Context,
    private val deviceRepository: DeviceRepository
) {
    private val gson = Gson()
    private val sceneListKey = stringPreferencesKey("scene_list")
    
    // 获取所有场景数据流
    val scenes: Flow<List<Scene>> = context.sceneDataStore.data
        .map { preferences ->
            val sceneJson = preferences[sceneListKey] ?: "[]"
            val type = object : TypeToken<List<Scene>>() {}.type
            gson.fromJson(sceneJson, type) ?: emptyList()
        }
    
    // 获取收藏场景数据流
    val favoriteScenes: Flow<List<Scene>> = scenes
        .map { sceneList ->
            sceneList.filter { it.isFavorite }
        }
    
    /**
     * 添加或更新场景
     */
    suspend fun addOrUpdateScene(scene: Scene) {
        context.sceneDataStore.edit { preferences ->
            val sceneJson = preferences[sceneListKey] ?: "[]"
            val type = object : TypeToken<MutableList<Scene>>() {}.type
            val sceneList: MutableList<Scene> = gson.fromJson(sceneJson, type) ?: mutableListOf()
            
            // 查找是否已存在此场景
            val existingIndex = sceneList.indexOfFirst { it.id == scene.id }
            
            if (existingIndex >= 0) {
                // 更新现有场景
                sceneList[existingIndex] = scene
            } else {
                // 添加新场景
                sceneList.add(scene)
            }
            
            preferences[sceneListKey] = gson.toJson(sceneList)
        }
    }
    
    /**
     * 删除场景
     */
    suspend fun deleteScene(sceneId: String) {
        context.sceneDataStore.edit { preferences ->
            val sceneJson = preferences[sceneListKey] ?: "[]"
            val type = object : TypeToken<MutableList<Scene>>() {}.type
            val sceneList: MutableList<Scene> = gson.fromJson(sceneJson, type) ?: mutableListOf()
            
            // 移除指定ID的场景
            sceneList.removeIf { it.id == sceneId }
            
            preferences[sceneListKey] = gson.toJson(sceneList)
        }
    }
    
    /**
     * 设置场景收藏状态
     */
    suspend fun setSceneFavorite(sceneId: String, isFavorite: Boolean) {
        context.sceneDataStore.edit { preferences ->
            val sceneJson = preferences[sceneListKey] ?: "[]"
            val type = object : TypeToken<MutableList<Scene>>() {}.type
            val sceneList: MutableList<Scene> = gson.fromJson(sceneJson, type) ?: mutableListOf()
            
            // 查找并更新场景的收藏状态
            val sceneIndex = sceneList.indexOfFirst { it.id == sceneId }
            if (sceneIndex >= 0) {
                val scene = sceneList[sceneIndex]
                sceneList[sceneIndex] = scene.copy(isFavorite = isFavorite)
                preferences[sceneListKey] = gson.toJson(sceneList)
            }
        }
    }
    
    /**
     * 获取指定ID的场景
     */
    suspend fun getSceneById(sceneId: String): Scene? {
        val sceneJson = context.sceneDataStore.data.map { it[sceneListKey] ?: "[]" }.firstOrNull()
        val type = object : TypeToken<List<Scene>>() {}.type
        val sceneList: List<Scene> = gson.fromJson(sceneJson, type) ?: emptyList()
        
        return sceneList.find { it.id == sceneId }
    }
    
    /**
     * 执行场景
     * 按顺序执行场景中的所有命令
     */
    suspend fun executeScene(sceneId: String): Boolean {
        val scene = getSceneById(sceneId) ?: return false
        
        // 执行场景中的所有命令
        scene.actions.forEach { action ->
            // 获取设备，如果设备不存在则跳过该命令
            val device = deviceRepository.getDeviceById(action.deviceId) ?: return@forEach
            
            // 更新设备的最后使用时间
            deviceRepository.updateDeviceLastUsed(device.id)
            
            // 根据不同的控制类型执行命令
            when (device.controlType) {
                com.example.remotecontrol.data.model.DeviceControlType.IR -> {
                    // 执行红外命令
                    val irData = device.irData ?: return@forEach
                    val command = irData.commandMap[action.command] ?: return@forEach
                    
                    // 这里应该调用红外管理器发送命令
                    // irManager.transmitNEC(irData.addressCode, command)
                }
                // 其他控制类型的实现...
                else -> { /* 暂不支持 */ }
            }
            
            // 如果设置了延迟，则等待指定时间
            if (action.delayAfter > 0) {
                Thread.sleep(action.delayAfter.toLong())
            }
        }
        
        return true
    }
    
    /**
     * 创建默认示例场景数据（仅用于测试）
     */
    suspend fun createSampleScenes() {
        // 创建一些示例设备
        val sampleScenes = listOf(
            Scene(
                name = "看电影模式",
                description = "自动设置家庭影院观影模式",
                actions = listOf(
                    Scene.Action(
                        deviceId = "sample_tv",
                        command = "POWER",
                        delayAfter = 1000
                    ),
                    Scene.Action(
                        deviceId = "sample_tv",
                        command = "SOURCE",
                        delayAfter = 500
                    ),
                    Scene.Action(
                        deviceId = "sample_ac",
                        command = "POWER",
                        delayAfter = 500
                    )
                ),
                isFavorite = true
            ),
            Scene(
                name = "睡眠模式",
                description = "关闭所有设备，准备睡觉",
                actions = listOf(
                    Scene.Action(
                        deviceId = "sample_tv",
                        command = "POWER",
                        delayAfter = 500
                    ),
                    Scene.Action(
                        deviceId = "sample_light",
                        command = "POWER",
                        delayAfter = 1000
                    )
                )
            )
        )
        
        // 保存示例场景数据
        context.sceneDataStore.edit { preferences ->
            preferences[sceneListKey] = gson.toJson(sampleScenes)
        }
    }
} 